package com.exam.api.config.interceptor;

import com.exam.api.common.web.TinyResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

public class TinyResponseInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(TinyResponseInterceptor.class);

    public TinyResponseInterceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Class<?> clazz = handlerMethod.getBeanType();
            Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(TinyResponse.class)) {
                log.debug("类{}包含注解{}", clazz.getCanonicalName(), TinyResponse.class.getCanonicalName());
                request.setAttribute("RESPONSE-WRAPPER-ANN", clazz.getAnnotation(TinyResponse.class));
            } else if (method.isAnnotationPresent(TinyResponse.class)) {
                log.debug("类{}的方法{}包含注解{}", clazz.getCanonicalName(), method.getName(), TinyResponse.class.getCanonicalName());
                request.setAttribute("RESPONSE-WRAPPER-ANN", method.getAnnotation(TinyResponse.class));
            }
        }

        return true;
    }
}
